package comply.zyc.controller;

import comply.zyc.Ku;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description:
 * @author: ZhaoYicong
 * @date: Created in 2020/6/21 22:29
 * @version: v1.0
 * @modified By:
 */

@WebServlet("/zhuce")
public class ZhuceServlet extends HttpServlet {
    String result;
    //实现用户注册的功能
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过请求 来获取 对应的数据
        String nameby=req.getParameter("username");
        String passwordby=req.getParameter("password");
        PrintWriter writer = resp.getWriter();
        Connection connection= Ku.getConnection();

        //通过用户名来检查和是否存在这样的用户
        try {
            PreparedStatement stmt = connection.prepareStatement("select * from loding where name=?");
            stmt.setString(1,nameby);
            ResultSet resultSet = stmt.executeQuery();

            //对用户判断后把数据传回去

           if(resultSet.next()){
               result="用户已经存在,不能注册";
               req.setAttribute("result",result);
               req.getRequestDispatcher("login.jsp").forward(req,resp);
               return;

           }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //注册新用户的逻辑代码。

        try {


            PreparedStatement stmt = connection.prepareStatement("insert into loding (name,password) value (?,?)");
            stmt.setString(1,nameby);
            stmt.setString(2,passwordby);
            int i = stmt.executeUpdate();
            System.out.println(i);

                result="注册成功 ";

            req.setAttribute("result",result);
            req.getRequestDispatcher("login.jsp").forward(req,resp);

        } catch (SQLException e) {
            e.printStackTrace();
        }

//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }




    }
}
